package com.itbaizhan;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *Calendar 类是一个抽象类，为我们提供了关于日期计算的功能
 * GregorianCalendar 是Calendar的子类  公历
 * */
/*注：月份的表示 ，一月是0，二月是1，以此类推，12月是11*/
public class TestCalendar {
    public static void main(String[] args) {
        //得到相关日期元素
        GregorianCalendar calendar = new GregorianCalendar
                (2049,10,1,12,30,20);
        System.out.println(calendar);
        printCalendar(calendar);
        int year = calendar.get(Calendar.YEAR);//打印2049
        int month = calendar.get(Calendar.MONTH);//打印月 10
        int day = calendar.get(Calendar.DAY_OF_MONTH);//1
        int day2 = calendar.get(Calendar.DATE);//1
        //Calendar.DAY_OF_MONTH和Calendar.DATE同义
        int date = calendar.get(Calendar.DAY_OF_WEEK);//打印2
        //星期几  这里是：1-7  星期日是1，星期一是2.。。。。星期六是7
        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
        System.out.println(day2);
        System.out.println(date);

        //设置日期
        GregorianCalendar calendar2 = new GregorianCalendar();
        calendar2.set(Calendar.YEAR,2049);
        calendar2.set(Calendar.MONTH,Calendar.OCTOBER);//月份数：0-11
        calendar2.set(Calendar.DAY_OF_MONTH,10);
        calendar2.set(Calendar.MINUTE,20);
        calendar2.set(Calendar.SECOND,23);
        printCalendar(calendar2);

        //日期计算
        GregorianCalendar calendar3 = new GregorianCalendar(2049,9,10,10,23,22);
        calendar3.add(Calendar.MONTH,-7);//月份-7
        calendar3.add(Calendar.DATE,7);//增加7
        printCalendar(calendar3);
        //日历对象和时间对象转化
        Date d = calendar3.getTime();
       // long d1 = calendar3.getTime().getTime();两个getTime才是显示毫秒
        GregorianCalendar calendar4 = new GregorianCalendar();
        calendar4.setTime(new Date());

    }
    static void printCalendar(Calendar calendar){
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;//因为从0开始计算
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int date = calendar.get(Calendar.DAY_OF_WEEK)-1;//星期几
        String week = ""+((date==0)?"日":date);
        int hour = calendar.get(Calendar.HOUR);
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        System.out.printf("%d年%d月%d日，星期%s %d:%d:%d\n",year,month,day,week,hour,minute,second);
    }
}
